/**
 * This class manages the login process.
 */
Ext.define('DCApp.LoginManager', {
    config: {
        /**
         * @cfg {Class} model
         * The model class from which to create the "user" record from the login.
         */
        model: null,

        /**
         * @cfg {Ext.data.Session} session
         */
        session: null
    },

    constructor: function (config) {
        this.initConfig(config);
    },

    applyModel: function(model) {
        return model && Ext.data.schema.Schema.lookupEntity(model);
    },
    logout:function(){
		Ext.Ajax.request({
            url: '/logout?token=' + Ext.util.Cookies.get("accessToken"),
            method: 'GET',
            headers: { 'Content-Type': 'application/json' },
            callback: function(opts,success, response){
            	var accessToken = Ext.util.Cookies.get("accessToken")
                Ext.util.Cookies.clear("accessToken");
            	if(accessToken!=null&&accessToken.indexOf("ST")>=0) {
            		var rstr = response.responseText;
            		//去掉多余的"
            		location.assign(rstr.substring(1,rstr.length-1));
            	}else{
            		//window.location.reload();
            		window.location.assign(this.url_home);
            	}
            },
            scope: this
        });
    },
    login: function(options) {
    	//for simdata
    	var req = {
            url: '/auth',
            async:false,  
            method: 'GET',
            params: options.data,
            scope: this,
            callback: this.onLoginReturn,
            original: options
        };
    	if(!DCApp.Cfg.SIM_ENM){
    		Ext.apply(req,{
    			method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                params : Ext.JSON.encode(options.data)
    		});
    	}
		Ext.Ajax.request(req);
    },

    onLoginReturn: function(options, success, response) {
        options = options.original;
        var session = this.getSession(),
            resultSet;

        if (success) {
            resultSet = this.getModel().getProxy().getReader().read(response, {
                recordCreator: session ? session.recordCreator : null
            });

            if (resultSet.getSuccess()) {
                var user = resultSet.getRecords()[0];
                DCApp.Cfg.usrInfo = user;
            		if(user.data!=null && user.data.token!=null) {
            		    Ext.util.Cookies.set("accessToken", user.data.token.accessToken);
            		}
                Ext.callback(options.success, options.scope, [resultSet.getRecords()[0]]);
                    return;
            }
        }

        Ext.callback(options.failure, options.scope, [response, resultSet]);
    }
});
